from conf.config import AppConf

from flask import Flask
from flask_sqlalchemy import SQLAlchemy

#用于记录日志
aiapp = Flask(__name__)

# 配置 MySQL 数据库连接
aiapp.config['SQLALCHEMY_DATABASE_URI'] = AppConf['ai']['db']['url']
aiapp.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
# 展示sql语句
aiapp.config['SQLALCHEMY_ECHO'] = False

db = SQLAlchemy(aiapp)


class FuncallInfo(db.Model):
    __tablename__ = 'funcall_info'
    __table_args__ = {'comment': '接口funcall调用日志'}
    id = db.Column(db.Integer, primary_key=True, comment='主键', autoincrement=True)
    description = db.Column(db.VARCHAR(512), nullable=True, comment='描述', server_default=db.text("''"))
    create_time = db.Column(db.TIMESTAMP, comment='创建时间', server_default=db.func.current_timestamp())
    req_args = db.Column(db.TEXT, nullable=True, comment='请求参数')
    #TEXT(16777216) 相当于 mediumtext
    log_text = db.Column(db.TEXT(16777216), nullable=True, comment='日志信息')
    remark = db.Column(db.VARCHAR(512), nullable=False, comment='备注', server_default=db.text("''"))
    type = db.Column(db.VARCHAR(16), nullable=False, comment='类型', server_default=db.text("'tool'"))
    status = db.Column(db.VARCHAR(8), nullable=False, comment='状态[0:正常,1:错误,2:执行]', server_default=db.text("'0'"))
    completion_tokens = db.Column(db.Integer, nullable=False, comment='完成令牌', server_default=db.text("'0'"))
    prompt_tokens = db.Column(db.Integer, nullable=False, comment='提示令牌', server_default=db.text("'0'"))
    total_tokens = db.Column(db.Integer, nullable=False, comment='总令牌', server_default=db.text("'0'"))

    # 查询的数据转字典
    def to_dict(self):
        model_dict = dict(self.__dict__)
        del model_dict['_sa_instance_state']
        return model_dict

def funcall_info_to_mysql(msg:FuncallInfo):
    with aiapp.app_context():
        if msg.id is None:
            db.session.add(msg)
            db.session.commit()  # 提交事务以保存到数据库
            # 刷新会话以获取新生成的主键
            db.session.flush()
            db.session.refresh(msg)
            # print(msg.__dict__)
        else:
            db.session.add(msg)
            db.session.commit()

# # 检查配置文件中是否包含数据库配置
# if 'db' in AppConf['ai']:
#
#         # def __repr__(self):
#         # return f'<FuncallInfo {self.id}>'
#
#     print("存在数据库配置")
# else:
#     class FuncallInfo():
#         id = None
#         description = None
#         create_time = None
#         req_args = None
#         log_text = None
#         remark = None
#     print("数据库配置未找到，跳过数据库初始化")